<?php

namespace app\xf\controller;

use app\xf\model\MapConfigModel;
use think\Controller;
use think\Request;

class MapConfigController extends BaseAdminController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        $data = MapConfigModel::find(1);
        return $this->SuccessReturn('ok', $data);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $all = $request->post();
//        $mapurl = array_key_exists('mapurl', $all) ? $all['mapurl'] : "";
//        $fileid = array_key_exists('fileid', $all) ? $all['fileid'] : 0;
        return $this->ErrorReturn(400, '不能添加');
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
        $all = $request->put();
        $mapurl = array_key_exists('mapurl', $all) ? $all['mapurl'] : "";
        $view = array_key_exists('view', $all) ? $all['view'] : '';
        $mapifo = MapConfigModel::find(1);
        $mapurl = rtrim($mapurl, '/');
        //检查mapurl 是否可用
        $token = $this->curlmapurl($mapurl . "/tokens/v1?access_token=none&secure");

        if (is_array($token) && $token['token'] != '') {
            if ($mapifo) {
                if ($mapurl != '') $mapifo->mapurl = $mapurl;
                if ($view != '') $mapifo->view = $view;
                $mapifo->save();
                return $this->SuccessReturn('ok', $mapifo);
            }
            return $this->ErrorReturn(500, '服务器错误');
        }
        return $this->ErrorReturn(400, '服务器地址有误 请确认');

    }

    public function curlmapurl($url)
    {
        $headerArray = array("Content - type:application / json;", "Accept:application / json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
        return $output;
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
